<?php
/**
 * 访问入口文件
 */

use Apps\BootStrap;
use Apps\Common\Constant\ExceptionConstant;
use Apps\Common\Controller\BaseController;
use Apps\Common\Model\BaseModel;
use Deyi\Functions\UtilFunction;
use Phalcon\Di\FactoryDefault;

if (!defined('ROOT_PATH')) {
    define('ROOT_PATH', dirname(__DIR__));
}
define('RUN_MODE', 'WEB');
require_once ROOT_PATH . '/Apps/Bootstrap.php';

try {
    $bootstrap = new BootStrap(new FactoryDefault());
    echo $bootstrap->handle()->getContent();
} catch (\Exception $e) {

    if ($e->getCode() == ExceptionConstant::REDIRECT_URL) {
        goto end;
    }

    BaseController::$THROW_ERR_CODE = $e->getCode();
    BaseModel::rollbackTransaction();

    $moduleName = strtolower($bootstrap->dispatcher->getModuleName());
    $controllerName = strtolower($bootstrap->dispatcher->getControllerName());
    $actionName = strtolower($bootstrap->dispatcher->getActionName());

    if (
        !in_array($e->getCode(), ExceptionConstant::LOG_SKIP_CONST) &&
        !strpos($e->getMessage(), 'was not found on handler') &&
        !strpos($e->getMessage(), 'registered in the application container') &&
        ($moduleName !== '1')
    ) {
        //异常日志记录
        $clientIp = UtilFunction::getClientIp();
        $routeUrl = $_SERVER['REQUEST_URI'];
        $filePath = str_replace(dirname(__DIR__), '', $e->getFile());
        $bootstrap->di->get('logger')->error("{$clientIp}:{$routeUrl} {$filePath}:" . $e->getLine() . ':' . $e->getMessage());
    }


    if (($moduleName === 'fanli' && strpos($e->getMessage(), 'was not found on handler')) || ($e->getCode() == ExceptionConstant::ROUTER_ERROR)) {

        if (!$bootstrap->request->isAjax() && $bootstrap->request->isGet()) {

            $bootstrap->view->enable();
            $bootstrap->view->setVars([
                'msg' => $e->getMessage()
            ]);
            $bootstrap->view->setViewsDir(ROOT_PATH . '/Apps/Fanli/Views/');
            $bootstrap->view->render('Spring', 'Notfound');

        } else {
            BaseController::renderJson($e->getCode(), [], $e->getMessage());
        }

    } else {
        if ($e->getCode() == ExceptionConstant::PAGE_ERROR) {
            echo $e->getMessage();
        } else {
            BaseController::renderJson($e->getCode(), [], $e->getMessage());
        }
    }
}

end:
//解锁接口请求互斥锁
BaseController::mutexUnlock();
